﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System;
using System.Collections.Generic;
#if NET35 || NET40
using System.Linq;

#elif NET20
using System.Collections.Generic;
using System.Data.SqlClient;
using Z.Net.Legacy20;
#endif
using System.Linq;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Sets SQL bulk update action.
        /// </summary>
        public void SetSqlMergeActionSingle()
        { 
            string sqlSetValue;
            string sqlWhere;
            string sqlInsertColumn;
            string sqlInsertValue;

            {
                IEnumerable<string> updateColumnSelectList = MappingList.Where(x => !Setting.PrimaryKeys.Contains(x.DestinationColumn) && x.DestinationColumn != Setting.IdentityColumn && x.DestinationColumn != TemporaryColumnName)
                    .Select(x => string.Format("[{0}]" + "=" + "@{1}", x.DestinationColumn, ParameterMapping[x.DestinationColumn]));
                IEnumerable<string> sqlWhereSelectList = Setting.PrimaryKeys.Select(x => string.Format("[{0}]" + "=" + "@{1}", x, ParameterMapping[x]));

                sqlSetValue = string.Join(", ", updateColumnSelectList.ToArray());
                sqlWhere = String.Join(" AND ", sqlWhereSelectList.ToArray());
            }

            {
                IEnumerable<string> updateColumnSelectList = MappingList.Where(x => x.DestinationColumn != Setting.IdentityColumn)
                    .Select(x => string.Format("[{0}]", x.DestinationColumn));
                IEnumerable<string> updateColumnInsertList = MappingList.Where(x => x.DestinationColumn != Setting.IdentityColumn)
                    .Select(x => string.Format("@{0}", ParameterMapping[x.DestinationColumn]));

                sqlInsertColumn = string.Join(", ", updateColumnSelectList.ToArray());
                sqlInsertValue = string.Join(", ", updateColumnInsertList.ToArray());
            }
            ; 


            SqlActionBulk1 = string.Format(SqlMergeActionSingle, SqlBulkCopy.DestinationTableName, TemporaryTableName, sqlSetValue, sqlWhere, sqlInsertColumn, sqlInsertValue);
        }
    }
}